package com.example.jiaju;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jiaju.Login.Login;
import com.example.jiaju.Login.LoginDao;
import com.example.jiaju.Login.LoginDaoDatabase;

import java.util.List;
import com.example.jiaju.R;
import com.gyf.immersionbar.ImmersionBar;


public class LoginActivity extends AppCompatActivity {

    EditText name;
    EditText password;
    TextView login;
    TextView zuce;
    LoginDaoDatabase loginDaoDatabase;
    LoginDao loginDao;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        ImmersionBar.with(this).statusBarDarkFont(true).init();

        name=findViewById(R.id.name);
        password=findViewById(R.id.password);

        login=findViewById(R.id.login);
        zuce=findViewById(R.id.resign);

        loginDaoDatabase= Room.databaseBuilder(this,LoginDaoDatabase.class,"User")
                .allowMainThreadQueries()
                .build();
        LoginDao loginDao=loginDaoDatabase.getLoginDao();

        SharedPreferences sp=getSharedPreferences("user",MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();

        login.setOnClickListener(view -> {
            Login user=new Login();
            user.username=name.getText().toString();
            user.password=password.getText().toString();

            List<Login> userlist=loginDao.findAllLogin();
            Boolean flag=true;
            for(Login user1:userlist){
                if(user1.username.equals(user.username)&&user1.password.equals(user.password)){
                    flag=false;
                    editor.putBoolean("isLogin",true).commit();
                    Intent intent=new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                }
            }
            if(flag)
                Toast.makeText(LoginActivity.this,"用户名或密码错误，请重新输入！",Toast.LENGTH_SHORT).show();
        });

        zuce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Login user=new Login();
                user.username=name.getText().toString();
                user.password=password.getText().toString();
                loginDao.insertLogin(user);
                Toast.makeText(LoginActivity.this,"注册成功！",Toast.LENGTH_SHORT).show();
                //loginDao.deleteLogin(user);
            }
        });
    }
}